package com.nf.health.app.fragment;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.models.BluetoothDeviceAttr;
import com.nf.health.app.service.BluetoothLeService;
import com.nf.health.app.service.SampleGattAttributes;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.bluetools.ProtocolParser;

@SuppressLint("NewApi")
public class HealthyBalanceFragment extends IBaseFragment implements
SensorEventListener {
	private static final String TAG = HealthyBalanceFragment.class.getSimpleName();
	private ImageView shake_bg;
	private TextView tv_shake_title;
	private SensorManager mSensorManager = null;
	private Vibrator mVibrator = null;
	private String mDeviceAddress = "";
	private int count = 0;
	// 蓝牙
	private byte[] b;
	private TextView tv_height, tv_weight, tv_fat, tv_bone, tv_jiroulv,
	tv_subCutaneousFat, tv_waterContent, tv_calorie, tv_age;
	private ScrollView scr_view;
	private RelativeLayout rl_shake;
	private boolean flg = true;

	private Button btn_data_commit;
	private int age;
	private int height;
	private float weight;
	private int fat;
	private int bone = 0;
	private int jiRou;
	private int piXiaZhiFang;
	private int shuiFen;
	private int bMR;
	private int user;
	private int sex;

	// Device scan callback.
	private BluetoothAdapter.LeScanCallback mLeScanCallback;
	private BluetoothAdapter mBluetoothAdapter;
	// 蓝牙服务类
	private BluetoothLeService mBluetoothLeService;
	private Handler mHandler = new Handler();
	private Handler mConnHandler = new Handler();
	private ServiceConnection mServiceConnection;
	private Runnable connRunnable;
	private Runnable runnable;
	/**
	 * Handles various events fired by the Service. 接收蓝牙服务传入的事件消息，或者是接收到的蓝牙数据
	 */
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				tv_shake_title.setText("蓝牙已连接");
				mConnHandler.removeCallbacks(connRunnable);
				flg = false;// 取消连接
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
					.equals(action)) {
				tv_shake_title.setText("蓝牙连接断开");
				flg = true;
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
					.equals(action)) {
				try {
					displayGattServices(mBluetoothLeService.getSupportedGattServices());
				} catch (Exception e) {
					LogUtil.exception(e);
				}
			} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
				byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
				if (data == null) {
					LogUtil.i(TAG, "数据暂时为空");
					return;
				}
				String msg = ProtocolParser.bytes2HexString(data);
				LogUtil.i(TAG, msg);
				if (!TextUtils.isEmpty(msg)) {
					if ("fd31000000000031".equals(msg) && count <= 3) {
						count++;
						if (count == 3) {
							count = 0;
							tv_shake_title.setText("连接失败，请重试~");
						}
					} else {
						try {
							flg = false;
							get10Code(msg);
						} catch (Exception e) {

						} finally {
							flg = false;// 取消震动
						}
					}
				}
			}
		}
	};

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		addViewFillInRoot(R.layout.fragment_balance_auto_input);

		initView();

		try {
			initBluetooth();
		} catch (Exception e) {
		}
	}

	private void initBluetooth() {
		// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
		if (!getActivity().getPackageManager().hasSystemFeature( PackageManager.FEATURE_BLUETOOTH_LE)) {
			showToast("不支持蓝牙4.0通讯");
			tv_shake_title.setText("该设备不支持蓝牙4.0通讯");
			return;
		}

		// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
		// final BluetoothManager bluetoothManager = (BluetoothManager)
		// getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		// 检查设备上是否支持蓝牙
		if (mBluetoothAdapter == null) {
			showToast("设备不支持蓝牙");
			return;
		}

		mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

			@Override
			public void onLeScan(final BluetoothDevice device, int rssi,
					byte[] scanRecord) {
				if(getActivity() == null)
				{
					return;
				}
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (device.getName().contains(BluetoothDeviceAttr.BALANCE_DEVICE_NAME)) {
							mDeviceAddress = device.getAddress();
							if(TextUtils.isEmpty(mDeviceAddress)){
								flg = true;
								tv_shake_title.setText("没有找到体脂秤，请重试");
								return;
							}
							tv_shake_title.setText("发现设备：" + device.getName()+"，连接中...");
							scanLeDevice(false);
							// 执行连接的操作
							if (mBluetoothLeService == null) {
								showToast("蓝牙服务未绑定!");
								return;
							}
							boolean connect = mBluetoothLeService.connect(mDeviceAddress);
							if(!connect){
								flg = false;
								tv_shake_title.setText("蓝牙连接失败， 请重试");
							}
//							connRunnable = new Runnable() {
//								@Override
//								public void run() {
//									if (mBluetoothLeService != null) {
//										try {
//											mBluetoothLeService.connect(mDeviceAddress);
//										} catch (Exception e) {
//											LogUtil.exception(e);
//											flg = false;
//											mHandler.removeCallbacks(connRunnable);
//											tv_shake_title.setText("蓝牙连接失败，请重试");
//										}
//										mHandler.postDelayed(connRunnable, 1000);
//									}
//
//								}
//							};
//							mHandler.postDelayed(connRunnable, 1000);
						}
					}
				});
			}
		};

		bindLeService();
		if (!mBluetoothAdapter.isEnabled()) {
			mBluetoothAdapter.enable();
		}

		mSensorManager = (SensorManager) getActivity().getSystemService(
				Service.SENSOR_SERVICE);
		mVibrator = (Vibrator) getActivity().getSystemService(
				Service.VIBRATOR_SERVICE);
	}

	private void initView() {
		tv_shake_title = (TextView) rootView.findViewById(R.id.tv_shake_title);
		shake_bg = (ImageView) rootView.findViewById(R.id.shake_bg);
		mSensorManager = (SensorManager) getActivity().getSystemService(
				Service.SENSOR_SERVICE);
		mVibrator = (Vibrator) getActivity().getSystemService(
				Service.VIBRATOR_SERVICE);

		rl_shake = (RelativeLayout) rootView.findViewById(R.id.rl_shake);
		scr_view = (ScrollView) rootView.findViewById(R.id.scr_view);
		tv_height = (TextView) rootView.findViewById(R.id.height);
		tv_weight = (TextView) rootView.findViewById(R.id.weight);
		tv_fat = (TextView) rootView.findViewById(R.id.fat);
		tv_bone = (TextView) rootView.findViewById(R.id.bone);
		tv_jiroulv = (TextView) rootView.findViewById(R.id.jiroulv);
		tv_subCutaneousFat = (TextView) rootView
				.findViewById(R.id.subCutaneousFat);
		tv_waterContent = (TextView) rootView.findViewById(R.id.waterContent);
		tv_calorie = (TextView) rootView.findViewById(R.id.calorie);
		tv_age = (TextView) rootView.findViewById(R.id.age);

		btn_data_commit = ViewUtil.getView(getActivity(), R.id.btn_data_commit);
		btn_data_commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				provider.requestAddDeviceBalance(String.valueOf(weight),
//						String.valueOf(height), String.valueOf(fat),
//						String.valueOf(bone), String.valueOf(jiRou),
//						String.valueOf(piXiaZhiFang), String.valueOf(shuiFen),
//						String.valueOf(bMR), String.valueOf(age),
//						"ADDDEVICEBALANCE");
			}
		});
		shake_bg.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				connect();
			}
		});
	}

	@Override
	public void handleActionSuccess(String actionName, Object object) {
		showToast((String) object);
		getActivity().finish();
	}



	@SuppressWarnings("deprecation")
	private void scanLeDevice(final boolean enable) {
		if (enable) {
			//			// Stops scanning after a pre-defined scan period.
			//			mHandler.postDelayed(new Runnable() {
			//				@Override
			//				public void run() {
			//					if(TextUtils.isEmpty(mDeviceAddress)){
			//						tv_shake_title.setText("未发现设备："+BluetoothDeviceAttr.BALANCE_DEVICE_NAME+",请重试");
			//						mBluetoothAdapter.stopLeScan(mLeScanCallback);
			//					}
			//				}
			//			}, 12000);
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			try {
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
			} catch (Exception e) {
				tv_shake_title.setText("初始化失败，请重试");
			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mSensorManager != null) {
			mSensorManager.registerListener(this,
					mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
					SensorManager.SENSOR_DELAY_NORMAL);
		}
		getActivity().registerReceiver(mGattUpdateReceiver,
				BluetoothLeService.makeGattUpdateIntentFilter());
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mSensorManager != null) {
			mSensorManager.unregisterListener(this);
		}
		if (mGattUpdateReceiver != null) {
			getActivity().unregisterReceiver(mGattUpdateReceiver);
		}
	}

	@Override
	public void onDestroy() {
		if (mHandler != null && runnable != null) {
			mHandler.removeCallbacks(runnable);
		}
//		if (mBluetoothAdapter != null) {
//			mBluetoothAdapter.disable();
//		}
		unbindService();
		super.onDestroy();
	}
	/**
	 * 绑定蓝牙服务和广播，Activity初始化需绑定蓝牙服务。
	 */
	public void bindLeService() {
		mServiceConnection = new ServiceConnection() {

			@Override
			public void onServiceConnected(ComponentName componentName,
					IBinder service) {
				mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
				if (!mBluetoothLeService.initialize()) {
					LogUtil.e(TAG, "Unable to initialize Bluetooth");
				}
			}

			@Override
			public void onServiceDisconnected(ComponentName componentName) {
				mBluetoothLeService = null;
			}
		};

		Intent bleService = new Intent(getActivity(), BluetoothLeService.class);
		getActivity().bindService(bleService, mServiceConnection,Context.BIND_AUTO_CREATE);
	}
	/**
	 * 取消绑定蓝牙服务和广播
	 */
	public void unbindService() {
		if (mServiceConnection != null) {
			getActivity().unbindService(mServiceConnection);
		}
		mBluetoothLeService = null;
	}

	/**
	 * 写入的指令数据 测试指令FE 03 01 00 AA 19 01 B0 byte[7] = byte[1]^....byte[6] 异或
	 * 
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public byte[] getByteData() {
		String sex = PreferenceHelper.getString(PreferenceHelper.USERSEX, "1");

		String height = PreferenceHelper.getString(PreferenceHelper.USERHEIGHT,
				"170");
		double doubleH = Double.parseDouble(height);
		int intH = (int) doubleH;
		b = new byte[8];
		b[0] = (byte) 0xfe;// 包头
		b[1] = (byte) 0x03;
		if (sex.equals("1")) {// 性别
			b[2] = (byte) 0x01;
		} else {
			b[2] = (byte) 0x00;
		}
		b[3] = (byte) 0x00;// 0普通 1业余 2专业
		b[4] = Integer.valueOf(intH).byteValue();// 身高
		try {
			SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
			Date date = s.parse(PreferenceHelper.getString(
					PreferenceHelper.BIRTHDAY, "1991-01-01"));
			int age = Util.getAgeByBirthday(date);
			if (age < 10) {
				age = 10;
			}
			b[5] = Integer.valueOf(age).byteValue();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		// b[4] = (byte) 0xaa;
		// b[5] = (byte) 0x19;
		b[6] = (byte) 0x01;// 单位 01千克 02lb(英石) 03ST:LB(英磅)
		b[7] = (byte) (b[1] ^ b[2] ^ b[3] ^ b[4] ^ b[5] ^ b[6]);
		return b;
	}

	// cf 11 9e a8 02a7 00000000000000000000
	// CF 03 98 A1 02A4 00000000000000000000
	public void get10Code(String msg) {
		String[] b = new String[(msg.length()) / 2];
		for (int i = 0; i < (msg.length()) / 2; i++) {
			b[i] = msg.trim().substring(i * 2, 2 * (i + 1));
		}
		user = Integer.parseInt(Util.toD(b[0], 16)) & 0x0f;
		sex = (Integer.parseInt(Util.toD(b[1], 16)) >> 7);
		age = Integer.parseInt(b[2], 16) & 127;
		height = Integer.parseInt(b[3], 16);
		int weightTemp = Integer.parseInt(b[4]+b[5], 16);
		fat = Integer.parseInt(b[6]+b[7],16);
		bone = Integer.parseInt(b[8], 16);
		jiRou = Integer.parseInt(b[9]+b[10],16);
		piXiaZhiFang = Integer.parseInt(b[11], 16);
		shuiFen = Integer.parseInt(b[12]+b[13], 16);
		bMR = Integer.parseInt(b[14]+b[15], 16);
		tv_height.setText(height + " CM");
		weight = weightTemp / 10.0f;
		tv_weight.setText(weight + " KG");
		tv_fat.setText(fat + "%");
		tv_bone.setText(bone + " KG");
		tv_jiroulv.setText(jiRou + "%");
		tv_subCutaneousFat.setText(piXiaZhiFang + " mm");
		tv_waterContent.setText(shuiFen + " ppm");
		tv_calorie.setText(bMR + " KG");
		if(age==10){
			tv_age.setText("小于"+age + " 岁");
		}else{
			tv_age.setText(age + " 岁");
		}

		rl_shake.setVisibility(View.GONE);
		scr_view.setVisibility(View.VISIBLE);
		// TODO 停止循环
		if (mHandler != null) {
			mHandler.removeCallbacks(runnable);
		}
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensorType = event.sensor.getType();
		float[] values = event.values;
		if (sensorType == Sensor.TYPE_ACCELEROMETER && flg) {
			if (Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14
					|| Math.abs(values[2]) > 14) {
				long[] pattern = { 500, 1000 };
				mVibrator.vibrate(pattern, -1);

				ObjectAnimator animator = ObjectAnimator.ofFloat(shake_bg, "translationX", 0, 100);
				animator.setRepeatCount(3);
				animator.setRepeatMode(ObjectAnimator.REVERSE);
				animator.start();

				tv_shake_title.setText("设备扫描中...");
				scanLeDevice(false);
				mDeviceAddress = "";
				scanLeDevice(true);
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	/**
	 * 根据UUID查找对应BLE
	 * 
	 * @param gattServices
	 */
	@SuppressLint("NewApi")
	private void displayGattServices(List<BluetoothGattService> gattServices) {
		if (gattServices == null)
			return;
		String uuid = null;
		// Loops through available GATT Services.
		for (BluetoothGattService gattService : gattServices) {
			// 获取服务列表
			uuid = gattService.getUuid().toString();

			LogUtil.i(TAG, "gattservice:"+uuid);
			if (uuid.equals(SampleGattAttributes.Balance.SERVICE_UUID)) {
				// 从当前循环所指向的服务中读取特征值列表
				List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
				// 对于当前循环所指向的服务中的每一个特征值
				for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
					uuid = gattCharacteristic.getUuid().toString();
					LogUtil.i(TAG, uuid);
					if (uuid.equals(SampleGattAttributes.Balance.NOTIFY_UUID)) {
						runnable = new Runnable() {
							@Override
							public void run() {
								// 要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
								if(mBluetoothLeService != null){
									mBluetoothLeService.readCharacteristic(gattCharacteristic);
									// 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
									try {
										mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
									} catch (Exception e) {
										mHandler.removeCallbacks(runnable);
									}
									mHandler.postDelayed(this, 500);
								}
							}
						};
						mHandler.postDelayed(runnable, 1000);
					} else if (uuid.equals(SampleGattAttributes.Balance.WRITE_UUID)) {
						gattCharacteristic.setValue(getByteData());
						mBluetoothLeService.writeCharacteristic(gattCharacteristic);
						tv_shake_title.setText("读取数据中...");
					}
				}
			}
		}
	}

	public void stopShake() {
		flg = false;
	}

	public void startShake() {
		flg = rl_shake.getVisibility() != View.GONE;
	}
	
	private void connect(){
		if(mBluetoothLeService!=null && !TextUtils.isEmpty(mDeviceAddress))
			mBluetoothLeService.connect(mDeviceAddress);
	}
}
